var express = require("express");
var app = express();
var fs = require('fs');

app.use(express.static("public"));

if (!fs.existsSync('./mes.json')) {
  fs.writeFileSync('./mes.json',[])
}




var userlist =JSON.parse(fs.readFileSync('./mes.json','utf-8')||"[]");
app.get("/register", function(req, res) {
  var userpass = req.query.userpass;
  var userpasstwo = req.query.userpasstwo;



  // console.log(req.query);
  for (var j = 0; j < userlist.length; j++) {
    if (userlist[j].username == req.query.username) {
      res.send("账号已被注册");
      return;
    }
  }
  userlist.push({
    username: req.query.username,
    userpass: req.query.userpass,
    userpasstwo: req.query.userpasstwo,
    age: req.query.age,
    sex: req.query.sex,
    major: req.query.major,
    love: req.query.love
  });

 

  if (userpass == userpasstwo) {
    var jsonStr = JSON.stringify(userlist);
    fs.writeFileSync('./mes.json', jsonStr);
    return res.redirect("index.html");
  } else {
    res.send('<script>alert("密码不一致");</script>');
  }

});



app.get("/login", function(req, res) {
  var username = req.query.username;
  var userpass = req.query.userpass;

  if (username=='') {
    res.send('账号为空')
  }
  var mes='账号不存在'

  for (var i = 0; i < userlist.length; i++) {
    if (userlist[i].username == username) {
      if (userlist[i].userpass == userpass) {
        // console.log(userlist);
        // res.send(getString(userlist[i]));
        // res.send('登录成功');
        mes=getString(userlist[i],userlist)
        break;
      } else {
        mes='密码错误'
      }
    } else {    
      mes='账号不存在'
    }
  }
  res.send(mes)
});

function getString(data,list) {
  // console.log(data);

  var liststr=``
  for(var i = 0; i < list.length; i++){
    liststr +=`
    <tr>
    <td>${list[i].username}</td>
    <td>${list[i].userpass}</td>
    <td>${list[i].age}</td>
    <td>${list[i].sex}</td>
    <td>${list[i].major}</td>
    <td>${list[i].love}</td>
    </tr>
    `
  }
  var str = `
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
            <meta name="author" content="林镭特">
            <title></title>
        </head>
        <body>
    `;
  str += `

      
        <table>
            <tr>
                <td>账号</td>
                <td>密码</td>
                <td>年龄</td>
                <td>性别</td>
                <td>专业</td>
                <td>爱好</td>

            </tr>
            ${liststr}
        </table>
        `;
  str += `</body></html>`;
  return str;
}

app.listen(5555, function() {
  console.log("服务器启动...");
});
